<?php
/**
 * Created by PhpStorm.
 * User: mocha
 * Date: 2018/10/29
 * Time: 17:23
 */

namespace app\index\controller;


use think\Db;
use think\Loader;
use think\Request;

class General extends Common
{

//    public function unlinkFile($path){
//        return file_exists($path) && unlink($path);
//    }

    /**
     * 附件上传
     * @return \think\response\Json
     */
    public  function saveFile()
    {
        $type = Request::instance()->param('type','staff','trim');#staff/demand/qualityIn/qualityOut
        $type_id = Request::instance()->param('type_id','','trim');
        $images = Request::instance()->param('image/a');
        $images_name = Request::instance()->param('image_name/a');

        $date = date('Ymd');
//        if(!$type_id){
//            return $this->error_msg('缺少参数');
//        }
//        $type = $type== 'staff'?'staff':'demand';

        $data = [];

        #===========

        if($images){

            for($i = 0;$i<count($images);$i++){
                $data['type_id'] = $type_id;
                $data['type'] = $type;
                $zj = strpos($images[$i], 'base64');
                if ($zj !== false) {
                    $file = $images[$i];
                    $start = strpos($file, ',');
                    $file = substr($file, $start + 1);
                    $file = str_replace(' ', '+', $file);
                    $data_file = base64_decode($file);
//                    $suffix = substr($images_name[$i],strpos($images_name[$i],'.'));
                    $filePath = ROOT_PATH . 'public' . DS . 'uploads'.DS .$date.DS .$type_id;
//                    if (!is_dir($filePath)){
//                        mkdir($filePath);
//                    }
                    $name = trim(trim($images_name[$i],'/'),'\\');
//                    $ff = explode('/', $fileName);//dump ($ff).'<br>';
                    if(!is_dir($filePath)){
                        mkdir($filePath,0777,true);
                    }

                    if(is_dir($filePath)){
                        $savePath = DS. 'public' . DS . 'uploads'.DS .$date.DS .$type_id.DS .$name;

                        # ==== 判断文件是否存在 start
                        $count = Db('enclosure')->where(['path'=>['like',"$savePath%"]])->count();
                        # 如果文件存在,则将文件名添加数字后缀

                        if($count){
                            $savePath .= '&?&?'."($count)";
                            # 获取文件后缀
                            $tmpArr = explode('.',$name);
                            $shuffle = end($tmpArr);
                            $tmpArr = explode(".$shuffle",$name);
                            $realName = current($tmpArr);

                            $fileName = $filePath.$realName."($count).".$shuffle;

                        }else{
                            $fileName = $filePath.'/'.$name;
                        }


                        # ==== end

                        $success = file_put_contents($fileName, $data_file);
                        if($success){
                            $data['path'] = $savePath;
                            $result = Db('enclosure')->insert($data);
                            if(!$result){
                                return $this->error_msg('上传失败！');
                            }
                        }else{
                            return $this->error_msg('上传失败！');
                        }
                    }else{
                        return $this->error_msg('上传失败！');
                    }

                }
            }

        }else{
            return $this->error_msg('上传失败！');
        }

        return $this->success_msg('上传成功！');

    }

    public function getFile(){
        $request = Request::instance();
        $id = $request->param('type_id','','trim');
        $type = $request->param('type','','trim');
        $page = $request->param('page',1,'intval');
        $rows = $request->param('rows',10,'intval');
        $begin_item = ($page-1)*$rows;

        if($type){
            $result = Db('enclosure')->field('id,path,modified')->where(['type'=>$type])->order('modified desc')->limit($begin_item,$rows)->select();
            $count = Db('enclosure')->field('path,modified')->where(['type'=>$type])->count();
            if($result){
                $finalResult = [];
                foreach($result as $re){
                    $path = $re['path'];
                    $fileName = explode('/',$path);
                    $fileName = end($fileName);
                    $fileName = explode('.',$fileName)[0];
                    if(strpos($path,'&?&?(')){
                        $namePath = explode('.',$path);
                        $shuffle = end($namePath);
                        $spath = substr($path,0,'-'.strlen('.'.$shuffle));
                        $arr1 = explode('&?&?',$shuffle);
                        $shuffle = $arr1[0];
                        $numStr = $arr1[1];

                        $path = $spath.$numStr.'.'.$shuffle;
                        $fileName .=$numStr;
                    }


                    $temp['id'] = $re['id'];
                    $temp['fileName'] = $fileName;
                    $temp['path'] = $path;
                    $temp['modified'] = $re['modified'];
                    $finalResult[] = $temp;
                }
                return $this->success_msg($finalResult,$count);
            }else{
                return $this->error_msg(1);
            }

        }else{
            $result = Db('enclosure')->field('path')->where(['type_id'=>$id])->select();

            if($result){
                $finalResult = [];
                foreach($result as $re){
                    if(strpos($re['path'],'&?&?(')){
//                        $arr1 = explode('&?&?',$re['path']);
//                        $numStr = end($arr1);
//                        $tempArr = explode('.',substr($re['path'],-1,strlen($numStr)));
//                        $shuffle = end($tempArr);
//                        $spath = substr($re['path'],-1,strlen('.'.$shuffle.'&?&?'.$numStr));


                        $namePath = explode('.',$re['path']);
                        $shuffle = end($namePath);
                        $spath = substr($re['path'],0,'-'.strlen('.'.$shuffle));
                        $arr1 = explode('&?&?',$shuffle);
                        $shuffle = $arr1[0];
                        $numStr = $arr1[1];
                        $finalResult[] = $spath.$numStr.'.'.$shuffle;
                    }else{
                        $finalResult[] = $re['path'];
                    }
                }
                return $this->success_msg($finalResult);
            }else{
                return $this->error_msg(1);
            }

        }


    }


    public function delFile(){

        $id = Request::instance()->param('id',57,'intval');

        $result = Db('enclosure')->where(['id'=>$id])->find();
        if($result){
            $savePath = $result['path'];
            if(strpos($savePath,'&?&?(')){
//                $arr1 = explode('&?&?',$savePath);
//                $numStr = end($arr1);
//                $tempArr = explode('.',substr($savePath,-1,strlen($numStr)));
//                $shuffle = end($tempArr);
//                $spath = substr($savePath,-1,strlen('.'.$shuffle.'&?&?'.$numStr));


                $namePath = explode('.',$savePath);
                $shuffle = end($namePath);
                $spath = substr($savePath,0,'-'.strlen('.'.$shuffle));
                $arr1 = explode('&?&?',$shuffle);
                $shuffle = $arr1[0];
                $numStr = $arr1[1];
                $path = ROOT_PATH.$spath.$numStr.'.'.$shuffle;
            }else{
                $path = ROOT_PATH.$savePath;
            }

            $result = Db('enclosure')->where(['id'=>$id])->delete();
            if($result){
                if(unlink($path)){
                    return $this->success_msg(1);
                }
            }
            return $this->error_msg(2);

        }else{
            return $this->error_msg('参数错误');
        }


    }


    /**
     * 状态更改
     * @return \think\response\Json
     */
    public function changeStatus(){
        $id = Request::instance()->param('id','','trim'); # 字符串1,2,3,4
        $status = Request::instance()->param('status','','trim');
        $user_id = Request::instance()->param('user_id','','trim');
        $type = Request::instance()->param('type','staff','trim');

        $type_map = [
            # 修改人员状态
            'staff' =>  [
                'staff_card', # 模型名
                'id',    # 查询的字段
                'status' # 修改的字段
            ],
            # 修改需求状态
            'demand'=>  [
                'company_demand',
                'demand_id',
                'customer_type'
            ],
            # 修改匹配状态
            'match' =>  [
                'match',
                'match_id',
                'status'
            ],

            # 修改收资质状态
            'qualityIn'=>  [
                'quality_card',
                'id',
                'status'
            ],
            # 修改出资质状态
            'qualityOut'=>  [
                'quality_demand',
                'quality_demand_id',
                'customer_type'
            ],
            # 修改匹配资质状态
            'qualityMatch'=>  [
                'quality_match',
                'quality_demand_id',
                'status'
            ],
        ];

        if(!in_array($type,array_keys($type_map))){
            return $this->error_msg('类型参数错误');
        }
        $model = $type_map[$type][0];
        $pk = $type_map[$type][1];
        $status_type = $type_map[$type][2];
//        $type = $type =='staff'?'staff_card':'demand_card';

        if(!$id){
            return $this->error_msg('参数错误');
        }
        $model = Loader::model($model);

        $result = $model->save([$status_type=>$status,'audio_time'=>time()],[$pk=>['IN',$id]]);


        if($result){
            return $this->success_msg(1);
        }else{
            return $this->error_msg(2);
        }

    }




}